package com.song.uaa.microservice.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * 安全工具类
 */
public class SecurityUtil {
	
	/**
	 * 从令牌声明中抽取权限
	 * @param claims 声明
	 * @return 权限
	 */
	public static List<GrantedAuthority> extractAuthorityFromClaims(Map<String, Object> claims) {
        return mapRolesToGrantedAuthorities(getRolesFromClaims(claims));
    }
	
	/**
	 * 从令牌声明中抽取权限
	 * @param claims 令牌声明
	 * @return 权限列表
	 */
	@SuppressWarnings("unchecked")
	private static Collection<String> getRolesFromClaims(Map<String, Object> claims) {
		return (Collection<String>) claims.getOrDefault("roles", new ArrayList<>());
	}
	
	/**
	 * 映射为角色
	 * @param roles
	 * @return
	 */
	private static List<GrantedAuthority> mapRolesToGrantedAuthorities(Collection<String> roles) {
        return roles.stream().map(role -> role.startsWith("ROLE_")? role : "ROLE_" + role).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }
}
